﻿using System.Collections.Generic;
using ApplicationLibrary.DBManager;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.SqlConnector;
using Fighter.Masters.ModuleData;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System;
using ApplicationLibrary;
using System.Data;
using System.IO;
using System.Globalization;
using ApplicationLibrary.CounterManager;
using Fighter.Fights.ModuleData;

namespace Fighter.Masters.Forms
{
    public partial class WebImport : ApplicationLibrary.DBManager.BatchForm
    {
        StringBuilder sb = new StringBuilder();
        CounterManager cm = new CounterManager(Counters.Athlete.Int(), 2014, Properties.Resources.CN_Athletes);

        public WebImport()
            : base("Title")
        {
            InitializeComponent();
        }

        #region Virtual Method


        protected override void OnAttachData()
        {
        }

        protected override void OnBatchExecute()
        {
            ClearMessage();

            bool ok = ImportClub() &&
                      ImportCoach() &&
                      ImportAthlete() &&
                      ImportFights();
        }
        #endregion
        
        private bool ImportClub()
        {
            bool ok = true;
            DRClub drClub = new DRClub(true);

            string result = GetXMLTable("Club");
            if (result.IsEmpty())
                return false;

            UpdateMessage("Cancellazione dati da tabella Club");
            int deleted = ClearTable(FG_Club.Name);
            UpdateMessage("Cancellati {0} clubs", deleted);

            DataSet ds = new DataSet();
            StringReader sr = new StringReader(result);
            ds.ReadXml(sr, XmlReadMode.Auto);

            for (int t = 0; t < ds.Tables["Club"].Rows.Count; t++)
            {
                string email = ds.Tables["Club"].Rows[t]["Email"].ToString().ToLower();
                string club = Capitalize(ds.Tables["Club"].Rows[t]["Nome"].ToString());
                string citta = Capitalize(ds.Tables["Club"].Rows[t]["Citta"].ToString());
                int regione = int.Parse(ds.Tables["Club"].Rows[t]["IdRegione"].ToString());
                string telefono = ds.Tables["Club"].Rows[t]["Telefono"].ToString();

                if (!drClub.Find(email))
                {
                    DataRow dr = drClub.AddRecord();
                    DataRowValues.SetValue<string>(dr, FG_Club.Mail, email);
                    DataRowValues.SetValue<string>(dr, FG_Club.Club, club);
                    DataRowValues.SetValue<string>(dr, FG_Club.City, citta);
                    DataRowValues.SetValue<int>(dr, FG_Club.Region, regione);
                    DataRowValues.SetValue<string>(dr, FG_Club.Phone, telefono);

                    if (!drClub.Update())
                    {
                        UpdateMessage("Errore con {0} {0}\r\n", email, club);
                        ok = false;
                    }
                }
            }
            if (ok)
                UpdateMessage("Inserimento di {0} club terminato senza problemi\r\n", ds.Tables["Club"].Rows.Count);

            return true;
        }
        private bool ImportCoach()
        {
            bool ok = true;
            DUCoach duCoach = new DUCoach();
            Dictionary<string, int> lastLine = new Dictionary<string, int>();
            string result = GetXMLTable("Allenatore");
            if (result.IsEmpty())
                return false;

            UpdateMessage("Cancellazione dati da tabella Allenatori");
            int deleted = ClearTable(FG_Coach.Name);
            UpdateMessage("Cancellati {0} allenatori", deleted);

            DataSet ds = new DataSet();
            StringReader sr = new StringReader(result);
            ds.ReadXml(sr, XmlReadMode.Auto);

            for (int t = 0; t < ds.Tables["Allenatore"].Rows.Count; t++)
            {
                string email = ds.Tables["Allenatore"].Rows[t]["Email"].ToString().ToLower();
                string fullname = Capitalize(ds.Tables["Allenatore"].Rows[t]["FullName"].ToString());
                string telefono = ds.Tables["Allenatore"].Rows[t]["Phone"].ToString();
                if (!lastLine.ContainsKey(email))
                    lastLine.Add(email, 0);

                lastLine[email]++;

                if (!duCoach.Find(email, lastLine[email]))
                {
                    DataRow dr = duCoach.AddRecord();
                    DataRowValues.SetValue<string>(dr, FG_Coach.Mail, email);
                    DataRowValues.SetValue<int>(dr, FG_Coach.Line, lastLine[email]);
                    DataRowValues.SetValue<string>(dr, FG_Coach.FirstName, fullname);
                    DataRowValues.SetValue<string>(dr, FG_Coach.Phone, telefono);

                    if (!duCoach.Update())
                    {
                        UpdateMessage("Errore con {0} {0}", email, fullname);
                        ok = false;
                    }
                }
            }
            if (ok)
                UpdateMessage("Inserimento {0} allenatori terminato senza problemi\r\n", ds.Tables["Allenatore"].Rows.Count);

            return ok;
        }
        private bool ImportAthlete()
        {
            bool ok = true;
            int lastId = int.MinValue;

            DRAthlete drAthlete= new DRAthlete(true);
            
            string result = GetXMLTable("Atleta");
            if (result.IsEmpty())
                return false;

            UpdateMessage("Cancellazione dati da tabella Atleti");
            int deleted = ClearTable(FG_Athlete.Name);
            UpdateMessage("Cancellati {0} atleti", deleted);

            DataSet ds = new DataSet();
            StringReader sr = new StringReader(result);
            ds.ReadXml(sr, XmlReadMode.Auto);

            for (int t = 0; t < ds.Tables["Atleta"].Rows.Count; t++)
            {
                string email = ds.Tables["Atleta"].Rows[t]["Email"].ToString().ToLower();
                int id = int.Parse(ds.Tables["Atleta"].Rows[t]["Id"].ToString());
                string fullName = Capitalize(ds.Tables["Atleta"].Rows[t]["FullName"].ToString());
                Gender gender = (Gender)Enum.Parse(typeof(Gender), ds.Tables["Atleta"].Rows[t]["Gender"].ToString());
                DateTime birthday = DateTime.Parse(ds.Tables["Atleta"].Rows[t]["BirthDay"].ToString(),
                                        CultureInfo.GetCultureInfo("en-us"),
                                        DateTimeStyles.None);
                Belts belt = (Belts)Enum.Parse(typeof(Belts), ds.Tables["Atleta"].Rows[t]["Belt"].ToString());
                float weight = Convert.ToSingle(ds.Tables["Atleta"].Rows[t]["Weight"].ToString(), CultureInfo.InvariantCulture.NumberFormat);
                string grapLevel = ds.Tables["Atleta"].Rows[t]["GrapplingLevel"].ToString();
                int fullContact = int.Parse(ds.Tables["Atleta"].Rows[t]["MatchFullContact"].ToString());
                int lowKick = int.Parse(ds.Tables["Atleta"].Rows[t]["MatchLowKick"].ToString());
                int k1Rules = int.Parse(ds.Tables["Atleta"].Rows[t]["MatchK1Rules"].ToString());

                if (id > lastId)
                    lastId = id;

                if (!drAthlete.Find(id))
                {
                    DataRow dr = drAthlete.AddRecord();

                    DataRowValues.SetValue<string>(dr, FG_Athlete.Mail, email);
                    DataRowValues.SetValue<int>(dr, FG_Athlete.ID, id);
                    DataRowValues.SetValue<string>(dr, FG_Athlete.FirstName, fullName);
                    DataRowValues.SetValue<Gender>(dr, FG_Athlete.Gender, gender);
                    DataRowValues.SetValue<DateTime>(dr, FG_Athlete.BirthDay, birthday);
                    DataRowValues.SetValue<float>(dr, FG_Athlete.Weight, weight);
                    DataRowValues.SetValue<Belts>(dr, FG_Athlete.Belt, belt);
                    DataRowValues.SetValue<string>(dr, FG_Athlete.GrapLevel, grapLevel);
                    DataRowValues.SetValue<int>(dr, FG_Athlete.FContMatch, fullContact);
                    DataRowValues.SetValue<int>(dr, FG_Athlete.LKickMatch, lowKick);
                    DataRowValues.SetValue<int>(dr, FG_Athlete.K1RulMatch, k1Rules);

                    if (!drAthlete.Update())
                    {
                        UpdateMessage("Errore con {0} {0}", email, fullName);
                        ok = false;
                    }
                }
            }

            if (ok)
            {
                UpdateMessage("Inserimento {0} atleti terminato senza problemi\r\n", ds.Tables["Atleta"].Rows.Count);
                cm.SetValue(lastId);
            }

            return ok;
        }
        private bool ImportFights()
        {
            bool ok = true;
            DRRegistration drReg = new DRRegistration(true);

            string result = GetXMLTable("Fights");
            if (result.IsEmpty())
                return false;

            UpdateMessage("Cancellazione dati da tabella Iscrizioni");
            int deleted = ClearTable(FG_Registration.Name);
            UpdateMessage("Cancellate {0} Iscrizioni", deleted);

            DataSet ds = new DataSet();
            StringReader sr = new StringReader(result);
            ds.ReadXml(sr, XmlReadMode.Auto);
            // point fight
            // full contact
            for (int t = 0; t < ds.Tables["Fights"].Rows.Count; t++)
            {
                string email = ds.Tables["Fights"].Rows[t]["Email"].ToString().ToLower();
                int idAthete = int.Parse(ds.Tables["Fights"].Rows[t]["Id"].ToString());
                string Iscrizioni = ds.Tables["Fights"].Rows[t]["Iscrizioni"].ToString();
                int evento = int.Parse(ds.Tables["Fights"].Rows[t]["IdEvento"].ToString());

                if (!drReg.Find(email, idAthete, evento))
                {
                    DataRow dr = drReg.AddRecord();
                    
                    DataRowValues.SetValue<string>(dr, FG_Registration.Mail, email);
                    DataRowValues.SetValue<int>(dr, FG_Registration.Athlete, idAthete);
                    DataRowValues.SetValue<int>(dr, FG_Registration.Fight, evento);

                    DataRowValues.SetValue<bool>(dr, FG_Registration.ChausLight, Iscrizioni[0] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.SavateAss, Iscrizioni[1] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.PointFight, Iscrizioni[2] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.LightContact, Iscrizioni[3] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.KickLight, Iscrizioni[4] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.K1Light, Iscrizioni[5] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.ThaiLight, Iscrizioni[6] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.MmaLight, Iscrizioni[7] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.Grapling, Iscrizioni[8] == '1');

                    DataRowValues.SetValue<bool>(dr, FG_Registration.ChaussCombact, Iscrizioni[9] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.SavateCombact, Iscrizioni[10] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.FullContact, Iscrizioni[11] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.LowKick, Iscrizioni[12] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.K1Rules, Iscrizioni[13] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.ThaiFull, Iscrizioni[14] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.MMAFull, Iscrizioni[15] == '1');
                    DataRowValues.SetValue<bool>(dr, FG_Registration.Checked, false);

                    if (!drReg.Update())
                    {
                        UpdateMessage("Errore con {0} {1}", email, idAthete);
                        ok = false;
                    }
                }
            }
            if (ok)
                UpdateMessage("Inserimento {0} iscrizioni terminato senza problemi\r\n", ds.Tables["Fights"].Rows.Count);

            return ok;         
        }

        private string GetXMLTable(string table)
        {
            UpdateMessage("Connessione col sito per scaricare dati dalla tabella {0}\n", table);
            string contents = string.Empty;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("http://win.wapsacitalia.it/GetTable.ashx?table={0}", table));
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                System.IO.Stream stream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(stream);
                contents = reader.ReadToEnd();
                UpdateMessage("Lettura eseguita correttamente");
            }
            catch (Exception exp)
            {
                UpdateMessage("Errore di comunicazione {0}\n", exp.Message);
            }
            finally
            {
            }

            return contents;
        }

        private int ClearTable(string table)
        {
            QueryBuilder qb = new QueryBuilder();
            qb.AddDelete();
            qb.AddFrom(table);

            SqlABCommand sqlCM = new SqlABCommand(qb.Query, GlobalInfo.DBaseInfo.dbManager.DB_Connection);
            return sqlCM.ExecuteNonQuery();

        }

        private void UpdateMessage(string mess)
        {
            sb.AppendLine(mess);
            txtResult.Text = sb.ToString();
            Application.DoEvents();
        }

        private void UpdateMessage(string format, params object[] mess)
        {
            sb.AppendLine(string.Format(format, mess));
            txtResult.Text = sb.ToString();
            Application.DoEvents();
        }

        private void ClearMessage()
        {
            sb.Clear();
            txtResult.Text = sb.ToString();
        }

        private string Capitalize(string text)
        {
            bool capitalize = true;
            string result = string.Empty;

            for (int t = 0; t < text.Length; t++)
            {
                if (capitalize)
                {
                    result += text[t].ToString().ToUpper();
                    capitalize = false;
                }
                else
                    result += text[t].ToString().ToLower();

                capitalize = text[t].ToString().IndexOfAny(new char[] { ' ', '.' }) != -1;
            }

            return result;
        }
    }
}